package cn.com.cetccst.compliancecheck.demo;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.com.cetccst.compliancecheck.ComplianceCheckManager;
import cn.com.cetccst.compliancecheck.demo.databinding.ActivityMainBinding;
import cn.com.cetccst.compliancecheck.demo.dialog.AppListDlg;
import cn.com.cetccst.compliancecheck.demo.dialog.CheckboxListDlg;
import cn.com.cetccst.compliancecheck.demo.dialog.ConfigInfoDlg;
import cn.com.cetccst.compliancecheck.demo.dialog.ConnectionSetDlg;
import cn.com.cetccst.compliancecheck.demo.dialog.GeoFenceSetDlg;
import cn.com.cetccst.compliancecheck.demo.dialog.TextListDlg;
import cn.com.cetccst.compliancecheck.demo.model.MainModel;

public class MainActivity extends AppCompatActivity {
    private static final String[] kFunctions = {
            "硬件型号", "操作系统", "应用黑名单", "地理位置", "连接验证", "当前配置和状态"};

    private static final String[] kDeviceModels = {
            "CET-AL00", "DCO-AL00", "TAS-AN00", "TEST-1", "TEST-2", "TEST-3", "TEST-4", "TEST-5", "TEST-6"};

    private static final String[] kOSVersion = {
            "9", "10", "11", "12", "13", "14", "15"};
    private MainModel mainModel;

    private static final String[] PERMISSIONS = ComplianceCheckManager.kPermissions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        mainModel = new MainModel();
        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        mainModel = new ViewModelProvider(this).get(MainModel.class);
        binding.setMainModel(mainModel);
        binding.setLifecycleOwner(this);
        checkPermission();
    }

    private void checkPermission() {
        Log.e("TestLog", "start check");
        for (String permission : PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                Log.e("TestLog", "request");
                ActivityCompat.requestPermissions(this, PERMISSIONS, 1000);
                break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_config) {
            config();
        } else if (id == R.id.menu_clear_log) {
            mainModel.clearLog();
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //checkPermission();
    }

    private void config() {
        TextListDlg.show(this, kFunctions, (dialogInterface, i) -> handleFunction(i));
    }

    private void handleFunction(int index) {
        switch (index) {
            case 0: {
                List<String> list = ComplianceCheckManager.getInstance().getDeviceModels();
                getMultiSelections(kDeviceModels, list, selections -> ComplianceCheckManager.getInstance().setDeviceModels(selections));
                break;
            }
            case 1: {
                List<String> list = ComplianceCheckManager.getInstance().getOSVersions();
                getMultiSelections(kOSVersion, list, selections -> ComplianceCheckManager.getInstance().setOSVersions(selections));
                break;
            }
            case 2: {
                List<String> list = ComplianceCheckManager.getInstance().getBlackListApp();
                AppListDlg.show(this, list, new AppListDlg.Callback() {
                    @Override
                    public void handleSelected(List<String> selectedAppList) {
                        ComplianceCheckManager.getInstance().setBlackListApp(selectedAppList);
                    }
                });
                break;
            }
            case 3: {
                GeoFenceSetDlg.show(this, new GeoFenceSetDlg.Callback() {
                    @Override
                    public void handleGeoFenceParams(double lng, double lat, float radius) {
                        if (radius > 0) {
                            ComplianceCheckManager.getInstance().setFenceParams(lat, lng, radius);
                        } else {
                            ComplianceCheckManager.getInstance().stopFence();
                        }
                    }
                });
                break;
            }
            case 4: {
                ConnectionSetDlg.show(this, new ConnectionSetDlg.Callback() {
                    @Override
                    public void handleOffLinePeriod(long offline) {
                        if (offline > 0) {
                            ComplianceCheckManager.getInstance().setMaxOffLinePeriod(offline * 1000);
                        } else if (offline == -1) {
                            ComplianceCheckManager.getInstance().setMaxOffLinePeriod(-1);
                        } else if (offline == -2) {
                            ComplianceCheckManager.getInstance().handleCheckInServerSuccess();
                        }
                    }
                });
                break;
            }
            case 5: {
                ComplianceCheckManager engine = ComplianceCheckManager.getInstance();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("硬件型号：");
                List<String> models = engine.getDeviceModels();
                for (String model : models) {
                    stringBuilder.append(model);
                    stringBuilder.append(";");
                }
                stringBuilder.append("\n");

                stringBuilder.append("系统版本：");
                List<String> osVersions = engine.getOSVersions();
                for (String osVersion : osVersions) {
                    stringBuilder.append(osVersion);
                    stringBuilder.append(";");
                }
                stringBuilder.append("\n");

                stringBuilder.append("应用限制：");
                List<String> appList = engine.getBlackListApp();
                for (String app : appList) {
                    stringBuilder.append(app);
                    stringBuilder.append(";");
                }
                stringBuilder.append("\n");

                stringBuilder.append("围栏：");
                double[] fence = engine.getFenceParams();
                if (fence != null) {
                    stringBuilder.append(String.format("[lng:%f][lat:%f][radius:%f]", fence[1], fence[0], fence[2]));
                }
                stringBuilder.append("\n");

                stringBuilder.append("连接检测：");
                long[] connectionParams = engine.getConnectionParams();
                if (connectionParams != null) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                    String dateStr = simpleDateFormat.format(new Date(connectionParams[1]));
                    String state = (System.currentTimeMillis() - connectionParams[0] - connectionParams[1]) > 0 ? "超时" : "未超时";
                    stringBuilder.append(String.format("[最大离线时间:%d秒][上次上线时间:%s][%s]", connectionParams[0] / 1000, dateStr, state));
                }
                stringBuilder.append("\n");

                ConfigInfoDlg.show(this, stringBuilder.toString());
                break;
            }
        }
    }

    private void getMultiSelections(String[] items, List<String> selectedItems, Callback callback) {
        boolean[] checked = new boolean[items.length];
        for (int i = 0; i < items.length; i++) {
            checked[i] = selectedItems.contains(items[i]);
        }
        CheckboxListDlg.show(this, items, checked, selected -> {
            List<String> ret = new ArrayList<>();
            for (int i = 0; i < items.length; i++) {
                if (selected[i]) {
                    ret.add(items[i]);
                }
            }
            callback.callback(ret);
        });
    }

    private interface Callback {
        void callback(List<String> selections);
    }
}